package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.cartoonutil.lib.BaseController;
import com.stark.cartoonutil.lib.CartoonsController;
import com.stark.cartoonutil.lib.StyleTransferController;
import com.stark.cartoonutil.lib.utils.ImgUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.SpecialAdapter;
import flc.ast.bean.MySpecialBean;
import flc.ast.bean.VisualAiFuncType;
import flc.ast.databinding.ActivityPicSpecialBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import jp.co.cyberagent.android.gpuimage.filter.GPUImageToonFilter;
import stark.common.apis.ApiManager;
import stark.common.apis.visionai.base.ImgStyleType;
import stark.common.base.IReqRetCallback;
import stark.common.basic.event.usersys.IUserSysEvent;
import stark.common.basic.event.usersys.UserSysEventProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class PicSpecialActivity extends BaseAc<ActivityPicSpecialBinding> {

    public static String imgPath;
    private Uri imgUri;
    private SpecialAdapter specialAdapter;
    private CartoonsController cartoonsController;
    private StyleTransferController styleTransferController;
    private int defWidth = -1;
    private int defHeight = -1;
    private boolean hasOpenSpecialEffect;
    private Bitmap mSpecialEffectBmp;
    private VisualAiFuncType mFuncType = VisualAiFuncType.FACE_PRETTY;

    private int oldPosition = 0;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_special;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPicSpecialBack.setOnClickListener((v) -> onBackPressed());
        mDataBinding.ivPicSpecialBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPicSpecialSave.setOnClickListener(this);
        mDataBinding.rvSpecialList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        specialAdapter = new SpecialAdapter();
        mDataBinding.rvSpecialList.setAdapter(specialAdapter);
        specialAdapter.setOnItemClickListener(this);
        mDataBinding.sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                GPUImageToonFilter filter = (GPUImageToonFilter) mDataBinding.gpuImgView.getFilter();
                filter.setLineSize(calLineSize(progress));
                mDataBinding.gpuImgView.requestRender();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        //yingxiang compare
        mDataBinding.ivImgCompare.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!hasOpenSpecialEffect) return true;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (oldPosition == 0) {
                            mDataBinding.ivRet.setVisibility(View.VISIBLE);
                            mDataBinding.glImgView.setVisibility(View.GONE);
                        } else if (oldPosition == 1) {
                            mDataBinding.ivRet.setVisibility(View.VISIBLE);
                            mDataBinding.gpuImgView.setVisibility(View.GONE);
                        }
                        Glide.with(mDataBinding.ivRet).load(imgUri).into(mDataBinding.ivRet);
                        break;
                    case MotionEvent.ACTION_UP:
                        mDataBinding.ivRet.setVisibility(View.GONE);
                        if (oldPosition == 0) {
                            mDataBinding.glImgView.setVisibility(View.VISIBLE);
                        } else if (oldPosition == 1) {
                            mDataBinding.ivRet.setVisibility(View.GONE);
                            mDataBinding.gpuImgView.setVisibility(View.VISIBLE);
                        } else {
                            mDataBinding.ivRet.setImageBitmap(mSpecialEffectBmp);
                            mDataBinding.ivRet.setVisibility(View.VISIBLE);
                        }
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPicSpecialSave:
                switch (oldPosition) {
                    case 0:
                        savePaintCartoon();
                        break;
                    case 1:
                        saveBeautifulCartoon();
                        break;
                    default:
                        saveSpecialEffect();
                        break;
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        specialAdapter.getItem(oldPosition).setSelected(false);
        specialAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        specialAdapter.getItem(position).setSelected(true);
        specialAdapter.notifyItemChanged(position);
        mDataBinding.sbProgress.setVisibility(View.INVISIBLE);
        switch (position) {
            case 0:
                paintCartoon();
                break;
            case 1:
                beautifulCartoon();
                mDataBinding.sbProgress.setVisibility(View.VISIBLE);
                break;
            case 2:
                UserSysEventProxy.getInstance().payEvent(this, new IUserSysEvent.IPayEventCallback() {
                    @Override
                    public void onPayOk(boolean isRealOk) {
                        if (isRealOk) {
                            oldEffect(70);
                        } else {
                            ToastUtils.showShort(getString(R.string.not_vip));
                        }
                    }
                });
                break;
            case 3:
                UserSysEventProxy.getInstance().payEvent(this, new IUserSysEvent.IPayEventCallback() {
                    @Override
                    public void onPayOk(boolean isRealOk) {
                        if (isRealOk) {
                            oldEffect(5);
                        } else {
                            ToastUtils.showShort(getString(R.string.not_vip));
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void initData() {
        List<MySpecialBean> list = new ArrayList<>();
        list.add(new MySpecialBean(R.drawable.ashouhui, getString(R.string.special_1), false));
        list.add(new MySpecialBean(R.drawable.ameishi, getString(R.string.special_2), false));
        list.add(new MySpecialBean(R.drawable.abianlao, getString(R.string.special_3), true));
        list.add(new MySpecialBean(R.drawable.anianq, getString(R.string.special_4), true));
        list.get(0).setSelected(true);
        specialAdapter.setList(list);

        imgUri = UriUtils.file2Uri(FileUtils.getFileByPath(imgPath));
        //该控制器用于对图片进行动漫化处理
        styleTransferController = new StyleTransferController(mContext, mDataBinding.glImgView);
        paintCartoon();
    }

    private void saveSpecialEffect() {
        if (!hasOpenSpecialEffect || mSpecialEffectBmp == null) {
            return;
        }
        showDialog(getString(com.stark.common.res.R.string.saving));
        RxUtil.create(new RxUtil.Callback<File>() {
            @Override
            public void doBackground(ObservableEmitter<File> emitter) {
                ImageUtils.save2Album(mSpecialEffectBmp, Bitmap.CompressFormat.JPEG);
                emitter.onNext(ImageUtils.save2Album(mSpecialEffectBmp, Bitmap.CompressFormat.JPEG));
            }

            @Override
            public void accept(File file) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_success));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(HomeActivity.class);
                    }
                }, 1000);
            }
        });
    }

    private void saveBeautifulCartoon() {
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                Bitmap bitmap = null;
                try {
                    bitmap = mDataBinding.gpuImgView.capture();
                    emitter.onNext(bitmap);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    emitter.onNext(bitmap);
                }
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                ToastUtils.showShort(getString(R.string.save_success));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(HomeActivity.class);
                    }
                }, 1000);
            }
        });
    }

    private void savePaintCartoon() {
        float aspectRatio = mDataBinding.glImgView.getWidth() * 1f / mDataBinding.glImgView.getHeight();
        cartoonsController.save(aspectRatio, new BaseController.ISaveCallback() {
            @Override
            public void onResult(@Nullable Uri fileUri) {
                dismissDialog();
                String srcPath = UriUtils.uri2File(fileUri).getPath();
                FileP2pUtil.copyPrivateImgToPublic(mContext, srcPath);
                ToastUtils.showShort(getString(R.string.save_success));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivity(HomeActivity.class);
                    }
                }, 1000);
            }
        });
    }

    private void paintCartoon() {
        mDataBinding.glImgView.setVisibility(View.VISIBLE);
        mDataBinding.ivRet.setVisibility(View.GONE);
        mDataBinding.gpuImgView.setVisibility(View.GONE);
        //该控制器用于对图片进行动漫化处理
        cartoonsController = new CartoonsController(mContext, mDataBinding.glImgView);

        showDialog(getString(R.string.loading));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (defWidth < 0) {
                    defWidth = mDataBinding.glImgView.getWidth();
                    defHeight = mDataBinding.glImgView.getHeight();
                }
                Bitmap bitmap = ImgUtil.Companion.getCompressedBitmapByFilePath(imgPath, defWidth, defHeight);
                ViewGroup.LayoutParams layoutParams = mDataBinding.glImgView.getLayoutParams();
                layoutParams.width = bitmap.getWidth();
                layoutParams.height = bitmap.getHeight();
                mDataBinding.glImgView.setLayoutParams(layoutParams);
                mDataBinding.glImgView.setImageSrc(bitmap.copy(bitmap.getConfig(), bitmap.isMutable()), true);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        cartoonsController.applyCartoonsModel(new BaseController.IApplyModelCallback() {
                            @Override
                            public void onComplete() {
                                dismissDialog();
                                hasOpenSpecialEffect = true;
                            }
                        });
                    }
                }, 500);
            }
        }, 500);
    }

    private void beautifulCartoon() {
        mDataBinding.glImgView.setVisibility(View.GONE);
        mDataBinding.ivRet.setVisibility(View.GONE);
        mDataBinding.gpuImgView.setVisibility(View.VISIBLE);
        mDataBinding.gpuImgView.setImage(FileUtils.getFileByPath(imgPath));
        mDataBinding.gpuImgView.setFilter(new GPUImageToonFilter());
        hasOpenSpecialEffect = true;
    }

    private float calLineSize(int progress) {
        float start = 0f;
        float end = 5.0f;
        return (end - start) * progress / 100f + start;
    }

    private void oldEffect(int value) {
        mFuncType = VisualAiFuncType.AGE_GENERATION;
        mDataBinding.glImgView.setVisibility(View.GONE);
        mDataBinding.gpuImgView.setVisibility(View.GONE);
        mDataBinding.ivRet.setVisibility(View.VISIBLE);
        openSpecialEffect(value);
    }

    /**
     * 打开特效
     */
    private void openSpecialEffect(@Nullable Integer value) {
        IReqRetCallback<Bitmap> callback = new IReqRetCallback<Bitmap>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable Bitmap result) {
                dismissDialog();
                ToastUtils.showShort(msg);
                if (result != null) {
                    mSpecialEffectBmp = result;
                    mDataBinding.ivRet.setImageBitmap(result);
                    hasOpenSpecialEffect = true;
                }
            }
        };
        showDialog(getString(R.string.handle_ing_text));
        switch (mFuncType) {
            case AGE_GENERATION:
                ApiManager.visionAiApi().ageGeneration(this, imgUri, value, callback);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //这里要释放资源
        if (cartoonsController != null) {
            cartoonsController.release();
            cartoonsController = null;
        }
        if (styleTransferController != null) {
            styleTransferController.release();
            styleTransferController = null;
        }
    }

}